import { login, logout, getInfo, getMenu } from '@/api/user'
// import {
//    getToken, setToken, removeToken,
//    getHospitalId, setHospitalId, removeHospitalId,
//    setUserId, getUserId, removeUserId,
//    setApiToken, getApiToken, removeApiToken,
//    setSysRole, getSysRole, removeSysRole
// } from '@/utils/auth'
import * as CookiesSave from '@/utils/auth'

import router, { resetRouter } from '@/router'

const state = {
  psw: CookiesSave.getPsw(),
  token: CookiesSave.getToken(),
  hospitalId: CookiesSave.getHospitalId(), // 获取医院ID
  hospitalName: CookiesSave.getHospitalName(), // 获取医院名字
  webcfg: CookiesSave.getWebcfg(), // 是否显示创伤
  userId: CookiesSave.getUserId(),
  apiToken: CookiesSave.getApiToken(),
  sysRole: CookiesSave.getSysRole(),
  meetPrefix: CookiesSave.getMeetPrefix(),
  consultationsId: '', // 会诊标识
  dataBus: {}, // 公共数据转存转运变量,赋值前先清空
  // consultationsId: CookiesSave.getConsultationsId(),
  name: CookiesSave.getName(),
  deptment: CookiesSave.getDeptment(),
  avatar: '',
  introduction: '',
  roles: CookiesSave.getRoles(),
  routerPowers: [],
  homePagePath: '',
}

const mutations = {
  SET_PSW: (state, psw) => {
    state.psw = psw
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_APITOKEN: (state, apitoken) => {
    state.apiToken = apitoken
  },
  SET_HOSPITAL_ID: (state, hospitalId) => {
    state.hospitalId = hospitalId
  },
  SET_HOSPITAL_NAME: (state, hospitalName) => {
    state.hospitalName = hospitalName
  },
  SET_WEBCFG: (state, webcfg) => {
    state.webcfg = webcfg
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
  },
  SET_MeetPrefix: (state, meetPrefix) => {
    state.meetPrefix = meetPrefix
  },
  SET_SYSROLE: (state, role) => {
    state.sysRole = role
  },
  SET_CONSULTATIONSID: (state, consultationsId) => {
    state.consultationsId = consultationsId
  },
  SET_DATABUS: (state, dataBus) => {
    state.dataBus = dataBus
  },

  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_DEPTMENT: (state, deptment) => {
    state.deptment = deptment
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ROUTERPOWERS: (state, routerPowers) => {
    state.routerPowers = routerPowers
  },
  SET_HOMEPATH: (state, homePagePath) => {
    state.homePagePath = homePagePath
  }
}
const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, md5Psd } = userInfo
    return new Promise((resolve, reject) => {
      login({
        mac: 'FFFFFFFFFFFF',
        email: username.trim(),
        password: md5Psd
      }).then(response => {
        console.log(response, 'response')
        if (response.code == 0) {
          const data = response.data
          const roleInfo = data
          const webcfg = roleInfo.svrcfg ? roleInfo.svrcfg.webcfg ? roleInfo.svrcfg.webcfg : '' : ''
          console.log('-----response---', response)

          commit('SET_PSW', password)
          CookiesSave.setPsw(password)
          commit('SET_TOKEN', data.token)
          CookiesSave.setToken(data.token)
          commit('SET_APITOKEN', roleInfo.token)
          CookiesSave.setApiToken(roleInfo.token)
          commit('SET_HOSPITAL_ID', roleInfo.hospitalId)
          CookiesSave.setHospitalId(roleInfo.hospitalId)

          commit('SET_HOSPITAL_NAME', roleInfo.hospitalName)
          CookiesSave.setHospitalName(roleInfo.hospitalName)

          commit('SET_MeetPrefix', roleInfo.MeetPrefix)
          CookiesSave.setMeetPrefix(roleInfo.MeetPrefix)
          commit('SET_USERID', roleInfo.doctorid)
          CookiesSave.setUserId(roleInfo.doctorid)
          commit('SET_NAME', roleInfo.name)
          CookiesSave.setName(roleInfo.name)
          commit('SET_DEPTMENT', roleInfo.Department)
          CookiesSave.setDeptment(roleInfo.Department)
          commit('SET_WEBCFG', webcfg)
          CookiesSave.setWebcfg(webcfg)

          const roleAuthority = roleInfo.userRoleList.map(item => item.roleName)
          roleInfo.authority && roleAuthority.push(roleInfo.authority)
          commit('SET_SYSROLE', JSON.stringify(roleAuthority)) // 存储角色数组名
          CookiesSave.setSysRole(JSON.stringify(roleAuthority))

          // console.log(roleInfo.sysRoles.map(item => item.name))
          commit('SET_ROLES', roleInfo.userRoleList.map(item => item.roleCode)) // 存储角色数组码
          CookiesSave.setRoles(roleInfo.userRoleList.map(item => item.roleCode))

          resolve()
        } else {
          reject(response)
        }

      }).catch(error => {
        console.log(error, 'error')
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo('admin-token').then(response => {
        const { data } = response
        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(error => {
        console.log('error---', error)
        reject(error)
      })
    })
  },

  // get user Menu
  getMenu({ commit, state }) {
    return new Promise((resolve, reject) => {
      getMenu(state.userId).then(response => {
        if (!response && response.length > 0) {
          reject('Verification failed, please Login again.')
        }
        // 过滤移动端菜单
        // const data = response.data[0].menu.filter(item => item.module && item.module.indexOf('4') > -1)
        // console.log(99887711, data)
        resolve(response.data[0].menu)
      }).catch(error => {
        console.log('error---', error)
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        CookiesSave.removeToken()
        commit('SET_ROLES', [])
        resetRouter()

        commit('SET_APITOKEN', '')
        CookiesSave.removeApiToken()
        commit('SET_HOSPITAL_ID', '')
        CookiesSave.removeHospitalId()
        commit('SET_USERID', '')
        CookiesSave.removeUserId()
        commit('SET_NAME', '')
        CookiesSave.removeName()
        commit('SET_DEPTMENT', '')
        CookiesSave.removeDeptment()
        commit('SET_SYSROLE', '')
        CookiesSave.removeSysRole()
        commit('SET_ROLES', '')
        CookiesSave.removeRoles()
        commit('SET_CONSULTATIONSID', '')

        // CookiesSave.removeConsultationsId()
        commit('SET_ROUTERPOWERS', [])
        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, {
          root: true
        })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_ROUTERPOWERS', [])
      CookiesSave.removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      CookiesSave.setToken(token)

      const {
        roles
      } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, {
        root: true
      })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, {
        root: true
      })

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
